﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;

namespace Framework
{
    public partial class ArticleDetail : System.Web.UI.Page
    {
        public DGSFrameworkEntities entity = new DGSFrameworkEntities();

        public List<udv_Categories> allCate = new List<udv_Categories>();
        public List<udv_Articles> allArt = new List<udv_Articles>();
        public udv_Articles articleDetails = new udv_Articles();
        public udv_ArticleComments articleComment = new udv_ArticleComments();
        MembershipUser currentUser;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                currentUser = Membership.GetUser();
                if (currentUser != null)
                {
                    lblUserName.Text = currentUser.Email;

                }
                else
                {
                    string returnUrl = Request.Url.PathAndQuery;
                    Response.Redirect("/login.aspx?url=" + returnUrl);
                }
                LoadCacheCategory();
                LoadCacheArticle();
                LoadArticleDetails();
                LoadArtilceComment();
                lblCountComment.Text = GetCountComment().ToString();

            }
        }

        public void LoadCacheCategory()
        {
            if (Cache["Category"] == null)
            {
                Cache["Category"] = allCate = entity.udv_Categories.ToList();
            }
            else
            {
                allCate = (List<udv_Categories>)Cache["Category"];
            }
        }

        public void LoadCacheArticle()
        {
            if (Cache["Article"] == null)
            {
                Cache["Article"] = allArt = entity.udv_Articles.Include("udv_Categories").ToList();
            }
            else
            {
                allArt = (List<udv_Articles>)Cache["Article"];
            }
        }

        public void LoadArticleDetails()
        {
            if (Request.QueryString["ArticleID"] != null)
            {
                int articleID;
                int.TryParse(Request.QueryString["ArticleID"].ToString(), out articleID);
                articleDetails = entity.udv_Articles.Where(ar => ar.ArticleID == articleID && ar.IsApproved == true).FirstOrDefault();
                if (articleDetails != null)
                {
                    string strUrlOriginal = ConfigPaths.Domain_Url + Globals.GetUrl(articleDetails.UrlRewrite, Globals.GetUrlAspx(articleDetails.UrlRewrite, false) + articleDetails.ArticleID);
                    if (CheckUrlOriginal(strUrlOriginal) == false)
                    {
                        Response.Redirect(strUrlOriginal);
                    }

                    articleDetails.udv_CategoriesReference.Load();
                   
                    ltrArticleTitle.Text = Globals.GetLanguage(articleDetails.Title, articleDetails.Title_en, true);
                    imgartdetail.ImageUrl = ConfigPaths.Path_ImageArticle_Folder.Substring(1) + articleDetails.ImageUrl;
                    imgartdetail.Width = 555;
                    imgartdetail.Height = 345;
                    lbldateartdetail.Text = articleDetails.AddedDate.ToString();
                    lbladdbyartdetail.Text = articleDetails.AddedBy;
                    ltrArticleContent.Text = Globals.GetLanguage(articleDetails.Body, articleDetails.Body_en, true);
                 
                   
                    
                }
                else
                {
                    Response.Redirect(ResolveUrl("~/" + Globals.GetUrl("Errors", "Errors.aspx")));
                }
            }
            else
            {
                Response.Redirect(ResolveUrl("~/" + Globals.GetUrl("Errors", "Errors.aspx")));
            }
        }

        public bool CheckUrlOriginal(string urlOriginal)
        {
            string strUrlRequest = ConfigPaths.Domain_Url.Substring(0, ConfigPaths.Domain_Url.Length - 1) + (Request.ServerVariables["HTTP_X_REWRITE_URL"] != null ? Request.ServerVariables["HTTP_X_REWRITE_URL"].ToString() : Request.RawUrl);
            if (strUrlRequest.ToLower().Trim() == urlOriginal.ToLower().Trim())
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public void LoadArtilceComment()
        {
            try
            {
                int artId = Int32.Parse(Request.QueryString["ArticleID"]);
                var artComment = from a in entity.udv_ArticleComments
                                 join u in entity.udv_Users on a.aspnet_Users.UserId equals u.UserID
                                 where a.udv_Articles.ArticleID == artId
                                 select new {
                                     a.Comment,
                                     a.AddedDate,
                                     u.Email,
                                     u.UserName                   
                                };
                                
                rptArticleComment.DataSource = artComment;
                rptArticleComment.DataBind();
            }
            catch (Exception)
            {

                throw;
            }
        }
        public int GetCountComment()
        {
            int cc = 0;
            int artId = Int32.Parse(Request.QueryString["ArticleID"]);
            try
            {
                int count = (from c in entity.udv_ArticleComments
                             where c.udv_Articles.ArticleID == artId
                             select c).Count();
                return cc = count;
            }
            catch (Exception)
            {

                throw;
            }
        }
        protected void btnSendArticleComment_Click(object sender, EventArgs e)
        {
            try
            {
                udv_ArticleComments commentInsert = new udv_ArticleComments();               
                var lstUser = Session["objMember"] as udv_Users;
                if (lstUser != null)
                {
                    int artId = Int32.Parse(Request.QueryString["ArticleID"]);
                    string contentComment = tbContentArticleComment.Text;
                    var user = entity.aspnet_Users.Where(d => d.UserId == lstUser.UserID).FirstOrDefault();
                    var artcomment = entity.udv_Articles.Where(a => a.ArticleID == artId).FirstOrDefault();
                    commentInsert.aspnet_Users = user;
                    commentInsert.udv_Articles = artcomment;
                    commentInsert.Comment = contentComment;
                    commentInsert.AddedDate = DateTime.Now;
                    entity.AddToudv_ArticleComments(commentInsert);
                    entity.SaveChanges();
                    tbContentArticleComment.Text = "";
                    LoadArtilceComment();
                }else
                {
                    Response.Redirect("/Login.aspx");
                }
               
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}